package com.newflypig.jblog.dao.hibernate;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.newflypig.jblog.dao.ISystemDAO;
import com.newflypig.jblog.model.BlogSystem;

@Repository("systemDao")
public class SystemDAOImpl extends BaseHibernateDAO<BlogSystem> implements ISystemDAO{

	@SuppressWarnings("unchecked")
	@Override
	public boolean checkLogin(String username, String password) {
		String hql ="from BlogSystem s "
				  + "where (s.key = :key_username and s.value = :username) "
				  + "or (s.key = :key_password and s.value = md5(:password))";
		List<BlogSystem> list =this.getSession()
			.createQuery(hql)
			.setString("key_username", BlogSystem.KEY_USERNAME)
			.setString("username", username)
			.setString("key_password", BlogSystem.KEY_PASSWORD)
			.setString("password", password)
			.list();
		
		return list.size() == 2;
	}

	@Override
	public String getValue(String key) {
		String hql = "from JblogSystem s where s.key = :key";
		
		return ((BlogSystem)this.getSession().createQuery(hql).setString("key", key).uniqueResult()).getValue();
	}

	@Override
	public void update(String key, String value) {
		String hql = "update BlogSystem s set s.value = :value where s.key = :key";
		
		this.getSession().createQuery(hql)
			.setString("value", value)
			.setString("key", key)
			.executeUpdate();
	}

	@Override
	public int updatePwd(String oldPwd, String newPwd) {
		String hql = "from BlogSystem s where s.key = :pwdKey and s.value = md5(:oldPwd)";
		Object o = this.getSession()
			.createQuery(hql)
			.setString("pwdKey", BlogSystem.KEY_PASSWORD)
			.setString("oldPwd", oldPwd)
			.uniqueResult();
		
		if(o == null)
			return 0;
		
		String updateHql = "update BlogSystem s set s.value = md5(:newPwd) where s.key = :pwdKey";
		this.getSession()
			.createQuery(updateHql)
			.setString("pwdKey", BlogSystem.KEY_PASSWORD)
			.setString("newPwd", newPwd)
			.executeUpdate();
		
		return 1;
	}

}
